import React from 'react';
import { observer, inject } from 'mobx-react';
import { withRouter } from 'react-router-dom';
import { Bubble, Tools, Toast } from 'weaver-mobile';
import { Browser, BrowserHrm } from 'weaver-mobile-page';
import { toJS } from 'mobx';
import loadjs from 'loadjs'

const onCloseHandle = () => {
  if (window.em) {
    window.em.closeWindow();
  } else {
    Bubble.error('em对象不存在', 0)
  }
}
const addShareMap = {
  'workplan': 2
}
const shareTypeMap = {
  '152': 'workflow',
  '37': 'doc',
  '18': 'crm',
  'workplan': 'workplan',
  '28': 'meeting'
}
const browserTitleMap = {
  '152': '流程',
  '37': '文档',
  '18': '客户',
  '28': '会议',
  'workplan': '日程'
}

@inject('entranceBasicStore')
@withRouter
@observer
export default class Home extends React.Component {

  getFrameParams() {
    let url = window.location.href;
    let urlParams = url.slice(url.indexOf('?') + 1).split('&');
    let params = [];
    urlParams.forEach(element => {
      let datas = element.split('=');
      params[datas[0]] = datas[1];
    });
    let host = url.slice(0, url.indexOf('/spa/'));
    params['host'] = host;
    return params;
  }

  openModalAfterLoad(params, res) {
    const { entranceBasicStore } = this.props;
    const { setPass, type } = entranceBasicStore;
    if (type) {
      setTimeout(() => {

        //init emobile config
        if (window.em) {
          window.em.ready(() => {
            window.em.config({
              corpId: res.em_corpid, //必填，企业的corpId
              appId: '' // 非必填，应用ID
            });
          })
        } else {
          // window.alert('em对象不存在');
          Bubble.error('em对象不存在', 0)
        }
        Toast.hide()
        setPass(true)
        // let urlParams = window.location.href.slice(window.location.href.indexOf('?'));
        // history.push(browser.path + urlParams)
      }, 100);
    }
  }

  componentDidMount() {
    const params = this.getFrameParams();
    const { entranceBasicStore } = this.props;
    const { addErrMsg } = entranceBasicStore;
    if (params['type'] && !entranceBasicStore.type) {
      entranceBasicStore.setType(params['type']);
    }
    if (params['em_auth_code']) {
      Toast.loading('Loading...');
      // Tools.ssoInit().then(() => {
      //   Toast.hide();
      //   setPass(true);
      // }).catch((res) => {
      //   Bubble.error(res.msg)
      // });
      Tools.callApi({
        url: '/api/ec/dev/app/test',
        method: 'GET',
        params: {
          em_auth_code: params['em_auth_code']
        },
      }).then((res) => {
        if (res.status === true && res.em_url_open) {

          let emUrl = res.em_url_open + '/open/js/jem.js'
          loadjs.isDefined('em')
            ? loadjs.ready('em', this.openModalAfterLoad.bind(this, params, res))
            : loadjs(emUrl, 'em', this.openModalAfterLoad.bind(this, params, res));

        } else {
          addErrMsg('认证失败: ' + JSON.stringify(res))
          // Bubble.error('认证失败，' + res.errmsg, 3, '24px', 1, onCloseHandle)
        }
      }, () => {
        addErrMsg('认证失败: 接口异常')
      });
    }
  }

  onChangeHandle(ids, names, datas) {
    const { entranceBasicStore } = this.props;
    const { addErrMsg, type } = entranceBasicStore;
    datas = toJS(datas)
    if (!type) {
      Bubble.error('获取资源类型失败', 3, '24px', 1, onCloseHandle)
      return false;
    }
    const params = this.getFrameParams();

    if (window.em) {
      window.em.getUserFromConversation({
        targetId: '', // 消息会话ID
        success: (res) => {
          if (typeof (res) === 'string') {
            res = JSON.parse(res);
          }

          // 以数组形式返回
          // 如：{"userIdList":["123","456"]"},"errMsg":"getUserListFromConversation:ok"}
          let userIdList = res.userIdList.join(',')
          let shareList = [];
          let successCount = 0;
          let errorMsg = '';
          datas.forEach(element => {
            let promise = new Promise(function (rs, rj) {
              let shareParams = {
                resourcetype: addShareMap[type] || type,
                resourceid: element.id,
                resourceids: userIdList
              }
              try {
                Tools.callApi({
                  url: '/api/common/chatResource/addshare',
                  method: 'POST',
                  params: {
                    ...shareParams
                  },
                }).then((res) => {
                  if (Object.keys(res).length === 0) {
                    rj(res)
                    return;
                  }
                  if (!res.success) {
                    rj(res)
                    return;
                  }
                  window.em.sendMsg({
                    targetId: '', // 消息会话ID
                    msgType: 10, // 消息类型：1-文本 2-链接 10-E6分享消息
                    msgInfo: {
                      content: element.name, // 分享标题（必填）
                      sharetype: shareTypeMap[type], // 分享数据类型,值有"doc","workflow","task","pdoc","folder" ,"crm" 分别代表文档，流程，任务，云盘文档，云盘文件，客户名片
                      sharetypename: params.sharetypename ? decodeURI(params.sharetypename) : '',
                      shareid: element.id, // 分享的数据ID（必填）
                      opentype_pc: 2,//PC端打开方式 1:应用内打开（默认） 2：PC默认浏览器打开
                      linkurl: res.linkUrl, // 消息链接地址（必填）
                      callbackurl: res.callbackurl,
                      canforward: 1
                    },
                    success: (res) => {
                      successCount++;
                    },
                    fail: (res) => {
                      if (typeof (res) === 'string') {
                        res = JSON.parse(res);
                      }
                      errorMsg = errorMsg + res.errMsg + ' '
                    },
                    complete: () => {
                      rs()
                    }
                  });
                })
              } catch (error) {
                Bubble.error('分享接口请求失败 ' + error, 3, '24px', 1, onCloseHandle)
                rj()
              }
            })
            shareList.push(promise);
          });
          Promise.all(shareList).then(() => {

            if (successCount === datas.length) {
              onCloseHandle()
            } else {
              Bubble.error(`共${datas.length}条，失败${datas.length - successCount}条 ` + errorMsg, 3, '24px', 1, onCloseHandle)
            }
          }).catch(() => {
            addErrMsg('promise fail')
            Bubble.error(`共${datas.length}条，失败${datas.length - successCount}条 ` + errorMsg, 3, '24px', 1, onCloseHandle)
          })
        },
        fail: (res) => {
          addErrMsg('getUserFromConversation 失败 ' + res.errMsg)
        }
      });
    } else {
      addErrMsg('没有em对象')
    }
  }


  render() {
    const { browser, passed, errMsg, type, isHrm, browserHrm } = this.props.entranceBasicStore;
    return (
      <div className='wea-emobile-entrance'>
        {errMsg && <div className='emobile-errmsg'>{errMsg}</div>}
        {passed && !isHrm && <Browser
          label={browserTitleMap[type]}
          store={browser}
          hasAdvanceSerach
          type={type}
          isSingle={false}
          dataParams={{ isFormEMShare: 1 }}
          conditionDataParams={{ isFormEMShare: 1 }}
          onChange={(ids, names, datas) => this.onChangeHandle(ids, names, datas)}>
          <span></span>
        </Browser>}
        {passed && isHrm && <BrowserHrm
          store={browserHrm}
          hasAdvanceSerach
          type={type}
          onChange={(ids, names, datas) => this.onChangeHandle(ids, names, datas)}
        />
        }
      </div>
    );
  }
}

